/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<iot25@lingyun>
 *                  All rights reserved.
 *
 *       Filename:  socket.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(24/04/25)
 *         Author:  LingYun <iot25@lingyun>
 *      ChangeLog:  1, Release initial version on "24/04/25 14:31:17"
 *                 
 ********************************************************************************/

#include "socket.h"



void *client_handler(void *arg)
{
    int clifd = -1;
    int rv = -1;
    char buf[1024];
    
    clifd = *(int *)arg;
    free(arg);
    
    while (g_server_running) {
        // 读取客户端数据
        memset(buf, 0, sizeof(buf));
        rv = read(clifd, buf, sizeof(buf) - 1);
        
        if (rv < 0) {
            fprintf(stderr, "Read client[%d] error: %s\n", clifd, strerror(errno));
            break;
        } else if (rv == 0) {
            printf("Client[%d] disconnected\n", clifd);
            break;
        } else {
            printf("Received %d bytes from client[%d]: %s\n", rv, clifd, buf);
            
            // 处理接收到的数据
            if (process_data(buf) < 0) {
                fprintf(stderr, "Failed to process data: %s\n", buf);
            }
        }
    }
    
    printf("Closing client socket: %d\n", clifd);
    close(clifd);
    
    return NULL;
}


int process_data(const char *data)
{
    char device_sn[64];
    long timestamp;
    float temperature;
    time_t receive_time;
    char sql[256];
    char *err_msg = NULL;
    int rc;
    
    if (!data || !g_db) {
        return -1;
    }
    
    // 解析数据格式：设备序列号,采样时间,采样温度
    if (sscanf(data, "%63[^,],%ld,%f", device_sn, &timestamp, &temperature) != 3) {
        fprintf(stderr, "Invalid data format: %s\n", data);
        return -1;
    }
    
    // 获取接收时间
    time(&receive_time);
    
    // 构造SQL语句
    snprintf(sql, sizeof(sql),
             "INSERT INTO temperature_records (device_sn, timestamp, temperature, receive_time) "
             "VALUES ('%s', %ld, %.3f, %ld);",
             device_sn, timestamp, temperature, receive_time);
    
    // 执行SQL语句
    rc = sqlite3_exec(g_db, sql, NULL, 0, &err_msg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", err_msg);
        sqlite3_free(err_msg);
        return -1;
    }
    
    printf("Data from %s stored in database. Temp: %.3f°C, Time: %s",
           device_sn, temperature, ctime(&timestamp));
    
    return 0;
}





